package sql;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import config.ServerConfig;

import data.BagData;
import data.Creature;
import data.CreatureList;
import data.StorageData;
import app.ServerApplication;

public class SqlManager {

	private static final Logger logger = LoggerFactory
			.getLogger(ServerApplication.class);

	private static SqlManager instance = null;

	private Connection con = null;

	private Statement stmt = null;

	private String url = null;

	private String user = null;

	private String pwd = null;

	private SqlManager() {
		url = ServerConfig.getValue("sqlUrl");
		user = ServerConfig.getValue("sqlUser");
		pwd = ServerConfig.getValue("sqlPwd");
	}

	public boolean connect() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, pwd);
			if (!con.isClosed()) {
				logger.info("connect database ok!");
				stmt = con.createStatement();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("connect database error");
			return false;
		}
		return true;
	}

	/**
	 * 新用户登录 在数据中插入用户信息
	 * 
	 * @return
	 */
	public boolean insertUser(Creature creature) {
		String query = "insert into user (accout, loginKey, username, sex, loginIp, loginTime)"
				+ " values (?, ?, ?, ?, ?, ?)";
		PreparedStatement preparedStmt;
		try 
		{
			preparedStmt = con.prepareStatement(query);
			preparedStmt.setString(1, creature.accout);
			preparedStmt.setString(2, creature.loginKey);
			preparedStmt.setString(3, creature.username);
			preparedStmt.setByte(4, creature.sex);
			preparedStmt.setString(5, creature.loginIp);
			preparedStmt.setLong(6, creature.loginTime);
			preparedStmt.execute();
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
			logger.error("creature :" + creature.accout + " register error!!!!");
			return false;
		}
		logger.info("creature :" + creature.accout + " register succeed!");
		return true;
	}

	/**
	 * 查询所有用户 初始化信息
	 * 
	 * @throws SQLException
	 */
	public void loadingUserInfo() throws SQLException {
		// 查询user表
		ResultSet rs = stmt.executeQuery("select * from user");
		while (rs.next()) {
			Creature creature = new Creature();
			creature.id = rs.getInt("id");
			creature.accout = rs.getString("accout");
			creature.loginKey = rs.getString("loginKey");
			creature.username = rs.getString("username");
			creature.sex = rs.getByte("sex");
			creature.loginTime = rs.getLong("loginTime");
			creature.loginIp = rs.getString("loginIp");
			creature.cash = rs.getInt("cash");
			creature.lv = rs.getShort("lv");
			creature.exp = rs.getInt("exp");
			InputStream is = rs.getBlob("storage").getBinaryStream();
			ObjectInputStream ois;
			try 
			{
				//数据库中读取对象
				ois = new ObjectInputStream(is);
				creature.storage = (StorageData)ois.readObject();
				is = rs.getBlob("bag").getBinaryStream();
				ois = new ObjectInputStream(is);
				creature.bag = (BagData)ois.readObject();
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			
			CreatureList.addLevLineUser(creature);
		}
	}

	/**
	 * 单例模式 取得SqlManager的唯一实例
	 * 
	 * @return
	 */
	public static SqlManager getInstance() {
		if (instance == null) {
			instance = new SqlManager();
		}
		return instance;
	}

}
